<template>
  <div class="login-container">
    <div class="login-view-form">
      <h1>{{ $t("ui.resetPassword.title") }}</h1>
      <a-form :model="resetPwdFormState" @submit.prevent="verifyMail">
        <a-form-item>
          <a-input
            v-model:value="resetPwdFormState.username"
            :placeholder="$t('ui.login.username')"
          >
            <template #prefix>
              <user-outlined />
            </template>
            <template #suffix>
              <a-tooltip :title="$t('ui.login.clear')">
                <close-outlined
                  class="pointer-icon"
                  @click="clearUsername"
                  style="color: rgba(0, 0, 0, 0.45)"
                />
              </a-tooltip>
            </template>
          </a-input>
          <div
            v-if="submittedUserMailAddress && usernameError"
            class="error-message"
          >
            {{ usernameError }}
          </div>
        </a-form-item>
        <a-form-item>
          <a-input
            type="email"
            v-model:value="resetPwdFormState.email"
            :placeholder="$t('ui.login.email')"
          >
            <template #prefix>
              <mail-outlined />
            </template>
            <template #suffix>
              <a-tooltip :title="$t('ui.login.clear')">
                <close-outlined
                  class="pointer-icon"
                  @click="clearEmail"
                  style="color: rgba(0, 0, 0, 0.45)"
                />
              </a-tooltip>
            </template>
          </a-input>
          <div
            v-if="submittedUserMailAddress && emailError"
            class="error-message"
          >
            {{ emailError }}
          </div>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" style="width: 100%" htmlType="submit">{{
            $t("ui.resetPassword.verifyMail")
          }}</a-button>
        </a-form-item>
      </a-form>
      <a-form
        v-if="hasSubmittedUserMailAddress"
        :model="formState"
        @submit.prevent="handleSubmit"
      >
        <a-form-item>
          <div class="verification-container">
            <a-input
              v-model:value="verificationCode"
              :placeholder="$t('ui.login.verificationCode')"
              style="flex: 1"
              :maxlength="6"
            >
              <template #prefix>
                <lock-outlined />
              </template>
            </a-input>
            <a-button
              @click="getVerificationCode"
              style="margin-left: 8px; flex-shrink: 0"
              >{{ $t("ui.login.getCode") }}</a-button
            >
          </div>
        </a-form-item>
        <a-form-item>
          <a-input-password
            v-model:value="formState.password"
            :placeholder="$t('ui.login.password')"
          >
            <template #prefix>
              <lock-outlined />
            </template>
          </a-input-password>
          <div v-if="submittedResetPwd && passwordError" class="error-message">
            {{ passwordError }}
          </div>
        </a-form-item>
        <a-form-item>
          <a-input-password
            v-model:value="formState.confirmPassword"
            :placeholder="$t('ui.login.confirm-password')"
          >
            <template #prefix>
              <lock-outlined />
            </template>
          </a-input-password>
          <div
            v-if="submittedResetPwd && confirmPasswordError"
            class="error-message"
          >
            {{ confirmPasswordError }}
          </div>
        </a-form-item>
        <a-form-item>
          <!-- <a-button @click="cancel">{{ $t("ui.login.cancel") }}</a-button> -->
          <a-button type="primary" htmlType="submit" style="width: 100%">{{
            $t("ui.resetPassword.enter")
          }}</a-button>
        </a-form-item>
      </a-form>
      <div class="login-link" style="float: right">
        <a-button type="link" @click="cancel">{{
          $t("ui.resetPassword.cancel")
        }}</a-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, computed, ref } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router"; // 导入 useRouter
import { useI18n } from "vue-i18n";
import {
  Form,
  FormItem,
  Input,
  InputPassword,
  Button,
  Tooltip,
} from "ant-design-vue";
import {
  UserOutlined,
  MailOutlined,
  CloseOutlined,
  LockOutlined,
} from "@ant-design/icons-vue"; // 导入图标

export default defineComponent({
  name: "RegisterForm",
  components: {
    "a-form": Form,
    "a-form-item": FormItem,
    "a-input": Input,
    "a-input-password": InputPassword,
    "a-button": Button,
    "a-tooltip": Tooltip,
    UserOutlined,
    MailOutlined,
    LockOutlined,
    CloseOutlined,
  },
  setup() {
    const { t } = useI18n(); // 获取 t 函数和 locale
    const store = useStore();
    const router = useRouter(); // 获取路由实例
    // 使用 Getters 获取 formState
    const resetPwdFormState = computed(
      () => store.getters["users/getResetPwdFormState"]
    );
    const formState = computed(() => store.getters["users/getFormState"]);
    const submittedUserMailAddress = ref(false); // 对于第一个表单
    const hasSubmittedUserMailAddress = ref(false);
    const submittedResetPwd = ref(false); // 对于第二个表单
    const verificationCode = ref("");
    // 其他的 computed 属性和方法
    const usernameError = computed(() =>
      resetPwdFormState.value.username.length > 3
        ? ""
        : t("ui.register.usernameMinLength")
    );
    const emailError = computed(() =>
      resetPwdFormState.value.email.includes("@")
        ? ""
        : t("ui.register.invalidEmail")
    );
    const passwordError = computed(() =>
      formState.value.password.length > 5
        ? ""
        : t("ui.register.passwordMinLength")
    );
    const confirmPasswordError = computed(() =>
      formState.value.confirmPassword === formState.value.password
        ? ""
        : t("ui.register.passwordsDoNotMatch")
    );
    // 验证状态
    const usernameValidateStatus = computed(() =>
      usernameError.value ? "error" : ""
    );
    const emailValidateStatus = computed(() =>
      emailError.value ? "error" : ""
    );
    const passwordValidateStatus = computed(() =>
      passwordError.value ? "error" : ""
    );
    const confirmPasswordValidateStatus = computed(() =>
      confirmPasswordError.value ? "error" : ""
    );
    const hasVarifiedMail = ref(false); // 新增一个ref变量跟踪是否验证邮箱
    const getVerificationCode = async () => {
      // 调用获取验证码的逻辑
      console.log("获取验证码:");
      alert("已发送验证码，请注意查收");
      hasVarifiedMail.value = true; // 新增一个ref变量跟踪是否验证邮箱
      // 可以在这里添加逻辑发送验证码到手机
    };

    const handleSubmit = () => {
      console.log("handleSubmit");
      submittedResetPwd.value = true; // 在验证前将submitted设置为true
      // store.commit("users/setIsRegistering", false); // 触发 Vuex mutation
      if (
        !usernameError.value &&
        !emailError.value &&
        !passwordError.value &&
        !confirmPasswordError.value
      ) {
        store.dispatch("users/resetPassword", {
          userData: {
            username: resetPwdFormState.value.username,
            verificationCode: verificationCode.value,
            name: resetPwdFormState.value.username,
            email: resetPwdFormState.value.email,
            newPassword: formState.value.password,
          },
        });
        store.commit("users/setIsForgotPassword", false); // 触发 Vuex mutation
      }
    };
    const verifyMail = () => {
      console.log("验证邮箱");
      console.log(resetPwdFormState);
      submittedUserMailAddress.value = true;
      if (!usernameError.value && !emailError.value) {
        hasSubmittedUserMailAddress.value = true;
        alert("已验证该账户的邮箱地址");
      }

      // 可以在这里添加验证邮箱逻辑
    };
    // 取消操作
    const cancel = () => {
      // 清空表单数据
      resetPwdFormState.value.username = "";
      resetPwdFormState.value.email = "";
      formState.value.username = "";
      formState.value.password = "";
      // formState.value.email = "";
      formState.value.confirmPassword = "";
      store.commit("users/setIsForgotPassword", false); // 触发 Vuex mutation
      router.push("/login"); // 登录成功后跳转到 Home 页面
      // 这里可以执行其他操作，例如跳转到登录页面
      console.log("取消操作");
    };
    const clearUsername = () => {
      resetPwdFormState.value.username = "";
    };
    const clearEmail = () => {
      resetPwdFormState.value.email = "";
    };
    return {
      verificationCode,
      resetPwdFormState,
      formState,
      usernameError,
      emailError,
      passwordError,
      confirmPasswordError,
      usernameValidateStatus,
      emailValidateStatus,
      passwordValidateStatus,
      confirmPasswordValidateStatus,
      hasVarifiedMail,
      verifyMail,
      getVerificationCode,
      handleSubmit,
      cancel,
      submittedUserMailAddress,
      hasSubmittedUserMailAddress,
      submittedResetPwd, // 将submitted添加到返回对象中
      clearUsername,
      clearEmail,
    };
  },
});
</script>

<style scoped>
.error-message {
  color: red;
}
.login-container {
  display: flex; /* 使用 Flexbox */
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  margin: 10vh;
  background-color: var(--bg-color);
  color: var(--info-color);
}

.login-view-form {
  width: 280px;
  /* background: white; 可选：表单背景颜色 */
  padding: 20px; /* 可选：内边距 */
  border-radius: 8px; /* 可选：圆角 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); /* 可选：阴影效果 */
}

.tabs-container {
  display: flex; /* 使用 Flexbox */
  justify-content: center; /* 水平居中 */
  /* margin-bottom: 16px; 添加底部间距 */
}

.flex-container {
  display: flex; /* 使用 Flexbox */
  justify-content: space-between; /* 使子项左右分离 */
  align-items: center; /* 垂直居中对齐 */
}

.verification-container {
  display: flex; /* 使用 Flexbox */
  width: 100%; /* 容器宽度为 100% */
}

.verification-container .ant-input {
  margin-right: 8px; /* 输入框和按钮之间的间距 */
}
/* 鼠标悬停时变为指针形状 */
.pointer-icon {
  cursor: pointer; /* 设置光标为 pointer */
}
</style>
